const Base = require('./base.js');
const {
  arrayGroup
} = require('../utils')
import {
  httpFormJson
} from '../utils/httpUtils'
const http = require('http');
const request = require('request');
module.exports = class extends Base {
  // 展示
  async indexAction() {
    let res = await this.model('admin').indexQueryProject();
    this.assign({
      result: res,
    })
    return this.display();

  }


  // 接口
  async apiAction() {
    let parmas = this.ctx.param('system_id')
    let result = await this.model('admin').adminData(parmas);
    let groupResult = arrayGroup(result.result)
    this.assign({
      result: groupResult,
      project: result.project
    })
    return this.display('index_show.html');
  }

  // 展示接口
  async showAction() {
    let parmas = {
      api_id: this.ctx.param('api_id')
    }
    let res = await this.model('admin').indexFindById(parmas);

    return think.isEmpty(res) ? this.json({
      success: false,
      result: res,
      msg: '查找失败'
    }) : this.json({
      success: true,
      result: res,
      msg: '查找成功'
    });

  }

  async sendApiResultAction() {

    let params = this.ctx.method === 'POST' ? this.ctx.post() : this.ctx.query;
    console.log(params);
    let result = await httpFormJson(params.path, JSON.parse(params.parmas), this.ctx.method, '');
    // if(result.body.success){
    let cookie = (result.headers['set-cookie']).toString().split(';')[0]
    this.cookie('cookie', cookie);
    this.json(result.body);
    // }else{
    //   this.json(result.body)
    // }


  }
  async sendAction() {

    let params = this.ctx.method === 'POST' ? this.ctx.post() : this.ctx.query;

    let cookie = this.cookie('cookie');
    let result = await httpFormJson(params.path, JSON.parse(params.parmas), this.ctx.method, cookie);
    if (result == null || result.statusCode === 403) {
      this.json({
        success: false,
        msg: '该接口需要授权'
      });
    } else {
      this.json(result.body);
    }


  }
  async clearAction() {
    this.cookie('cookie', '');
    this.json({
      success: true
    });
  }
};